<script setup lang="ts">
// 移除Window接口声明，改为导入类型
import CanvasArea from './components/CanvasArea.vue'; // 引入画布组件
import LeftPanel from './components/LeftPanel.vue'; // 引入左侧面板组件
import RightPanel from './components/RightPanel.vue'; // 引入右侧面板组件
import { registerComponents } from './components/library'; // 引入组件库
import { generateProjectFiles, type ExportedFile, prepareProjectExportData, type ProjectExportData } from '@/utils/codeGenerator'; // 引入代码生成工具
import { Ship, Box, View, Moon, Sunny, Close, Monitor } from '@element-plus/icons-vue'; // 引入图标
import { ref, onMounted, onUnmounted, nextTick, getCurrentInstance, computed, watch } from 'vue'; // 引入 Vue API
import MiniblinkExportWizard from './components/MiniblinkExportWizard.vue'; // 导入 Miniblink 导出向导组件
import { useDesignStore, type CanvasComponent } from '@/stores/designStore'; // Import store and type
import { ElNotification, ElLoading, ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash-es'; // 引入cloneDeep
import { MiniblinkExporter } from './utils/miniblinkExporter'; // 导入 Miniblink 导出工具
import componentFactory from './utils/componentFactory';
import Preview from './components/preview/Preview.vue'; // 导入新的预览组件
import previewService from './services/PreviewService';
import themeService from './services/ThemeService'; // 导入主题服务
import VueProjectExportDialog from './components/VueProjectExportDialog.vue'; // 导入Vue项目导出对话框

// 定义Electron API接口
interface ElectronAPI {
  invoke(channel: 'handle-export-project', files: ExportedFile[]): Promise<ExportResult>;
  invoke(channel: 'handle-export-for-miniblink', projectData: ProjectExportData): Promise<ExportResult>;
  invoke(channel: 'handle-export-source', projectData: ProjectExportData): Promise<ExportResult>;
  on(channel: string, callback: (payload: any) => void): RemoveListenerFunction;
}

// 定义导出结果接口
interface ExportResult {
  success: boolean;
  message?: string;
  filePath?: string;
}

// 定义移除监听器函数类型
type RemoveListenerFunction = () => void;

// 处理导出按钮点击
const isExporting = ref(false);

// Existing export (source code)
const isExportingSource = ref(false);
const isExportingMiniblink = ref(false);

// 内部状态 - 用于 loading dialog
const isLoading = ref(false);
const loadingText = ref('处理中...');

// --- Loading Dialog Logic ---
function showLoading(text = '处理中...') {
  loadingText.value = text;
  isLoading.value = true;
}

function closeLoading() {
  isLoading.value = false;
}

// --- Export Source Logic ---
let removeProgressListener: (() => void) | null = null;

const handleExportSource = async () => {
  if (isExportingSource.value) return;
  isExportingSource.value = true;
  showLoading('准备导出源代码...');

  try {
    const projectData: ProjectExportData = prepareProjectExportData();

    if (window.electronAPI?.invoke) {
      // Main process will send detailed progress via 'export-progress' event
      const result = await window.electronAPI.invoke('handle-export-source', projectData);
      
      closeLoading(); // Close loading before showing final message
      await nextTick(); // Wait for loading to close visually

      if (result?.success) {
        ElNotification({
          title: '成功',
          message: result.message || '源代码导出完成！',
          type: 'success',
          duration: 5000
        });
        console.info(result.message || '源代码导出完成！');
      } else {
        ElNotification({
          title: '错误',
          message: result?.message || '源代码导出失败。',
          type: 'error',
          duration: 7000
        });
        console.error(result?.message || '源代码导出失败。');
      }
    } else {
      closeLoading(); // Close loading on error too
      ElNotification({
        title: '环境检查失败',
        message: '导出功能仅在 Electron 环境下可用',
        type: 'warning',
        duration: 5000
      });
      console.warn('不在 Electron 环境或 IPC 不可用，无法执行导出。');
      console.error('导出功能仅在 Electron 环境下可用。');
    }
  } catch (error: any) {
    closeLoading(); // Close loading on error too
    ElNotification({
      title: '导出错误',
      message: `导出源代码处理失败: ${error?.message || error}`,
      type: 'error',
      duration: 10000
    });
    console.error('导出源代码处理失败:', error);
    console.error(`导出过程中发生错误: ${error?.message || error}`);
  } finally {
    isExportingSource.value = false;
    // closeLoading() is called within try/catch now
  }
};

// --- Electron IPC ---
onMounted(() => {
  // 注册组件库组件，添加全局标志防止重复注册
  if (!window.__componentsRegistered) {
    const app = getCurrentInstance()?.appContext.app;
    if (app) {
      registerComponents(app);
      window.__componentsRegistered = true;
    }
  }

  // Set up Electron IPC listener for export progress updates
  if (window.electronAPI?.on) {
    const removeListener = window.electronAPI.on('export-progress', (payload: any) => {
      console.log('Renderer received progress:', payload.status);
      showLoading(payload.status); // Update loading text
    });
    
    if (removeListener) {
      removeProgressListener = removeListener;
    }
  }
});

// Clean up listener when component is unmounted
onUnmounted(() => {
  if (removeProgressListener) {
    removeProgressListener();
    removeProgressListener = null;
  }
});

// 在适当位置，增加以下状态变量
const miniblinkWizardVisible = ref(false);
const miniblinkExportResult = ref({ success: false, message: '' });

// 添加预览相关状态
const isPreviewVisible = ref(false);
const previewComponents = ref<CanvasComponent[]>([]);
const canvasWidth = ref(600);
const canvasHeight = ref(400);

// 监听设计状态变化，实时更新预览
watch(() => useDesignStore().canvasComponents, (newComponents) => {
  // 只有当预览窗口打开时才更新预览组件
  if (isPreviewVisible.value) {
    previewComponents.value = cloneDeep(newComponents);
    console.log('[App] 更新预览组件数据');
  }
}, { deep: true });

// 处理预览功能
const handlePreview = async () => {
  // 从设计器存储获取当前画布组件
  const designStore = useDesignStore();
  
  // 深拷贝组件数据，避免预览时修改到原始设计数据
  const sourceComponents = cloneDeep(designStore.canvasComponents);
  
  // 获取画布尺寸 - 使用设计器中的实际画布尺寸
  canvasWidth.value = designStore.canvasSize.width;
  canvasHeight.value = designStore.canvasSize.height;
  
  // 显示预览窗口
  if (sourceComponents.length > 0) {
    // 保存到预览组件状态
    previewComponents.value = sourceComponents;
    isPreviewVisible.value = true;
  } else {
    ElMessage.info('画布上没有组件可供预览');
  }
};

// 处理预览关闭
const handlePreviewClose = () => {
  isPreviewVisible.value = false;
  // 可以在这里添加额外清理逻辑
};

/**
 * 处理Miniblink导出
 */
const handleExportForMiniblink = async () => {
  if (isExportingMiniblink.value) return;
  
  // 声明在try块外部
  let loadingInstance: any = null;
  
  try {
    isExportingMiniblink.value = true;
    
    // 显示加载指示器
    loadingInstance = ElLoading.service({
      fullscreen: true,
      lock: true,
      text: '准备导出...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    console.log('开始导出 Miniblink 文件');
    
    // 生成项目名称 (简单的日期格式)
    const projectName = `EasyWindow_${new Date().toISOString().split('T')[0].replace(/-/g, '')}`;
    
    // 获取设计数据
    const store = useDesignStore();
    
    // 获取画布样式
    const canvasElement = document.querySelector('.canvas-content') as HTMLElement;
    const canvasStyle = {
      backgroundColor: '#ffffff',
      borderWidth: 1,
      borderStyle: 'solid',
      borderColor: '#cccccc',
      borderRadius: 0
    };
    
    if (canvasElement) {
      // 从DOM获取画布样式
      const computedStyle = window.getComputedStyle(canvasElement);
      canvasStyle.backgroundColor = computedStyle.backgroundColor || canvasStyle.backgroundColor;
      canvasStyle.borderWidth = parseInt(computedStyle.borderWidth) || canvasStyle.borderWidth;
      canvasStyle.borderStyle = computedStyle.borderStyle || canvasStyle.borderStyle;
      canvasStyle.borderColor = computedStyle.borderColor || canvasStyle.borderColor;
      canvasStyle.borderRadius = parseInt(computedStyle.borderRadius) || canvasStyle.borderRadius;
      
      console.log('获取到的画布样式:', canvasStyle);
    }
    
    // 先使用文件对话框让用户选择保存位置
    loadingInstance.setText('请选择保存位置...');
    
    if (!window.electronAPI?.invoke) {
      throw new Error('无法访问Electron API，导出功能需要在Electron环境中运行');
    }
    
    // 使用showSaveDialog让用户选择保存位置
    const dialogResult = await window.electronAPI.invoke('show-save-dialog', {
      title: '选择Miniblink导出位置',
      defaultPath: `index.html`,
      buttonLabel: '保存',
      filters: [
        { name: 'HTML文件', extensions: ['html'] }
      ]
    });
    
    // 如果用户取消了选择，则中止导出
    if (dialogResult.canceled || !dialogResult.filePath) {
      loadingInstance.close();
      isExportingMiniblink.value = false;
      return;
    }
    
    const savePath = dialogResult.filePath;
    const skipBrowserDownload = true; // 由于已经有了保存对话框，设置为true跳过浏览器下载
    
    loadingInstance.setText('正在导出文件...');
    
    // 创建导出器
    const exporter = new MiniblinkExporter();
    
    // 调用导出方法
    const result = await exporter.export({
      components: store.canvasComponents,
      productName: projectName,
      savePath: savePath, // 使用用户选择的路径
      canvasSize: store.canvasSize,
      canvasStyle: canvasStyle,
      skipBrowserDownload: skipBrowserDownload
    });
    
    loadingInstance.close();
    isExportingMiniblink.value = false;
    
    if (result.success) {
      ElMessage.success(`Miniblink 文件导出成功: ${result.filePath}`);
    } else {
      const errorMessage = result.message || '未知错误';
      ElMessage.error(`导出失败: ${errorMessage}`);
    }
  } catch (error) {
    console.error('导出过程中发生错误:', error);
    if (loadingInstance) {
      loadingInstance.close();
    }
    isExportingMiniblink.value = false;
    ElMessage.error(`导出失败: ${error instanceof Error ? error.message : String(error)}`);
  }
};

/**
 * 创建组件
 * @param {String} componentName 组件名称
 * @returns {Object} 组件配置
 */
const createComponent = (componentName) => {
  // 使用组件工厂创建组件
  return componentFactory.createComponent(componentName)
}

// 主题相关逻辑
const currentTheme = computed(() => themeService.currentTheme.value);
const themeIcon = computed(() => currentTheme.value === themeService.ThemeType.LIGHT ? Moon : Sunny);
const themeTooltip = computed(() => currentTheme.value === themeService.ThemeType.LIGHT ? '切换到暗色模式' : '切换到亮色模式');

// 切换主题
const toggleTheme = () => {
  themeService.toggleTheme();
};

// 添加Vue导出对话框状态
const isVueProjectExportDialogVisible = ref(false);

// 处理Vue项目导出按钮点击
const handleExportVueProject = () => {
  isVueProjectExportDialogVisible.value = true;
};

// 处理Vue项目导出对话框关闭
const handleVueExportDialogClose = () => {
  isVueProjectExportDialogVisible.value = false;
};

// 使用设计存储
const designStore = useDesignStore();
</script>

<template>
  <el-container class="main-container">
    <el-header class="main-header">
      <span>Easy Window Designer</span>
      <div class="header-buttons">
        <!-- Preview Button -->
        <el-button
          type="success"
          :icon="View"
          @click="handlePreview"
          size="small"
          title="预览当前设计"
        >
          预览
        </el-button>
        <!-- Export Source Button -->
        <el-button
          type="info"
          :icon="Box"
          @click="handleExportSource"
          :loading="isExportingSource"
          size="small"
          title="导出项目源代码 (用于二次开发)"
          :disabled="isExportingMiniblink"
        >
          导出源码
        </el-button>
        
        <!-- Vue Project Export Button -->
        <el-button
          type="warning"
          :icon="Monitor"
          @click="handleExportVueProject"
          size="small"
          title="导出为Vue项目 (保留交互逻辑)"
          :disabled="isExportingMiniblink || isExportingSource"
        >
          导出Vue项目
        </el-button>
        
        <!-- Miniblink Export Button -->
        <el-button
          type="primary"
          :icon="Ship"
          @click="handleExportForMiniblink"
          :loading="isExportingMiniblink"
          size="small"
          title="导出Miniblink项目 (可在C#、易语言等环境中使用)"
          :disabled="isExportingSource"
        >
          导出Miniblink
        </el-button>
        <!-- Theme Toggle Button -->
        <el-button
          type="default"
          :icon="themeIcon"
          @click="toggleTheme"
          size="small"
          :title="themeTooltip"
        ></el-button>
      </div>
    </el-header>
    
    <el-container class="main-content">
      <!-- 左侧面板 -->
      <LeftPanel />
      
      <!-- 中间画布区域 -->
      <CanvasArea class="canvas-area" />
      
      <!-- 右侧属性面板 -->
      <RightPanel />
    </el-container>
    
    <!-- Miniblink导出向导 -->
    <MiniblinkExportWizard
      v-model:visible="miniblinkWizardVisible"
      :export-result="miniblinkExportResult"
    />
    
    <!-- Vue项目导出对话框 -->
    <VueProjectExportDialog
      v-model:visible="isVueProjectExportDialogVisible"
      @close="handleVueExportDialogClose"
    />
    
    <!-- 预览组件 -->
    <div v-if="isPreviewVisible" class="preview-overlay">
      <div class="preview-modal">
        <div class="preview-header">
          <span>效果预览</span>
          <el-button size="small" type="danger" @click="handlePreviewClose" link>
            关闭
          </el-button>
        </div>
        <div class="preview-body">
          <Preview
            :components="previewComponents"
            :canvas-width="canvasWidth"
            :canvas-height="canvasHeight"
          />
        </div>
      </div>
    </div>
  </el-container>
</template>

<style>
/* 全局样式，确保 html, body 和 #app 占满高度 */
html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
}
/* --- 全局覆盖 Element Plus 按钮间距 --- */
.canvas-content > .rendered-component.el-button + .rendered-component.el-button {
    margin-left: 0 !important;
}
</style>

<style scoped>
.main-container {
  height: 100%;
  display: flex;
  flex-direction: column; /* 确保 Header 在上面 */
}

.main-header {
  background-color: var(--header-bg-color, #f5f7fa); /* 使用CSS变量 */
  color: var(--text-color, #303133); /* 使用CSS变量 */
  line-height: 60px;
  padding: 0 20px;
  border-bottom: 1px solid var(--border-color, #e4e7ed); /* 使用CSS变量 */
  flex-shrink: 0; /* 防止 Header 被压缩 */
  display: flex;
  align-items: center;
  justify-content: space-between; /* 标题左对齐，按钮右对齐 */
}

.main-header span {
  font-weight: bold;
  font-size: 18px;
}

.header-buttons {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
}

.main-content {
  flex-grow: 1; /* 让内容区域填充剩余空间 */
  overflow: hidden; /* 防止内部滚动条影响布局 */
  display: flex;
  background-color: var(--bg-color, #ffffff); /* 使用CSS变量 */
}

.canvas-area {
  background-color: var(--canvas-bg-color, #f0f2f5); /* 使用CSS变量 */
  padding: 0; /* 移除内边距，让画布组件完全控制 */
  flex-grow: 1; /* 画布区域填充剩余空间 */
  overflow: auto; /* 如果画布内容超出，允许滚动 */
  position: relative; /* 为内部绝对定位元素提供基准 */
}

/* 预览覆盖层样式 */
.preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-modal {
  /* width: 800px; */
  max-width: 90%;
  /* max-height: 90%; */
  background-color: var(--bg-color, #ffffff);
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--border-color, #e4e7ed);
}

.preview-header span {
  font-size: 16px;
  font-weight: 500;
}

.preview-body {
  padding: 16px;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 